from fastapi import APIRouter, Depends, Request, Form, Response
from fastapi.security import OAuth2PasswordRequestForm

from app.core.BaseResponse import success
from app.model import mysql
from app.service.captcha import captcha_service
from app.service.jwt_service import get_current_user
from app.service import login_service
from app.service.login_service import user_logout
from app.validator.app import schemas
# from tortoise.functions import Max

router = APIRouter()


# async def test():
#     user = await mysql.User.all(id=Max("id"))
#     return


async def send_captcha(
        user: schemas.SendCaptchaVal,
):
    """
    发送验证码
    :param user:
    :return:
    """
    code = await captcha_service(mobile=user.mobile, types=1)
    res = {"captcha": code}
    return success(data=res)


async def login(
        request: Request,
        user: schemas.LoginVal,
):
    """
    登录
    :param request:
    :param user:
    :return:
    """
    login_info = await login_service.login(request, user, user.captcha)
    return success(login_info)


async def invitation_code(
        code: schemas.CodeVal,
        current_user: schemas.User = Depends(get_current_user),
):
    """
    绑定邀请码
    :param code:
    :param current_user:
    :return:
    """
    await login_service.invitation_code(code, current_user)

    return success()


async def logout(
        current_user: schemas.User = Depends(get_current_user),
):
    """
    退出
    :param current_user:
    :return:
    """
    await user_logout(current_user.id)
    return success()


async def login_debug(
        form_data: OAuth2PasswordRequestForm = Depends()
):

    access_token = await login_service.login_debug(mobile=form_data.username)
    return {"access_token": access_token, "token_type": "bearer"}

